package org.easy.socket.server.processor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.easy.socket.server.ClientSession;
import org.easy.socket.server.DataModel;
import org.easy.socket.server.manager.IClientManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smartboot.socket.StateMachineEnum;
import org.smartboot.socket.extension.processor.AbstractMessageProcessor;
import org.smartboot.socket.transport.AioSession;
import org.smartboot.socket.transport.WriteBuffer;

import java.io.IOException;
import java.util.Objects;

/**
 * @Description:
 * @Author: wxl
 * @CreateTime: 2023/1/16 14:13
 */
public class EasyServerMessageProcessor extends AbstractMessageProcessor<String> {

    private static final Logger logger = LoggerFactory.getLogger(EasyServerMessageProcessor.class);

    private AioSession session;

    private final IClientManager clientManager;

    public EasyServerMessageProcessor(IClientManager clientManager) {
        this.clientManager = clientManager;
    }

    @Override
    public void process0(AioSession aioSession, String s) {
        logger.info("从客户端收到的消息:{}",s);
        JSONObject object = JSON.parseObject(s);
        if (!object.containsKey("state")) {
            String clientId = object.getString("clientId");
            AioSession session = getClientManager().getSession(clientId);

            logger.info("客户端ID为:{}",clientId);
        }
    }

    @Override
    public void stateEvent0(AioSession aioSession, StateMachineEnum stateMachineEnum, Throwable throwable) {
        if (stateMachineEnum == StateMachineEnum.NEW_SESSION) {
            this.session = aioSession;
            DataModel dataModel = new DataModel(aioSession.getSessionID());
            dataModel.setState(stateMachineEnum);
            sendToClient(JSON.toJSONString(dataModel));
        }
        ClientSession clientSession = new ClientSession(session, stateMachineEnum);
        getClientManager().addSession(clientSession);
    }

    public void sendToClient(String data){
        WriteBuffer writeBuffer = this.session.writeBuffer();
        try {
            byte[] bytes = data.getBytes();
            writeBuffer.writeInt(bytes.length);
            writeBuffer.write(bytes);
        } catch (IOException e) {
            logger.error("向服务端发送消息异常:{}",e.getMessage());
        }
    }

    public IClientManager getClientManager() {
        return clientManager;
    }
}
